﻿''' <summary>
''' 内存块管理区域
''' </summary>
Public Class BufferChunkManage
    ''' <summary>
    ''' 总的虚拟块数
    ''' </summary>
    Private m_ChunkCapacity As Integer
    ''' <summary>
    ''' 内存缓冲区最大长度
    ''' </summary>
    Private m_numBytes As Integer
    ''' <summary>
    ''' 内存块缓冲区
    ''' </summary>
    Private m_buffer As Byte()
    ''' <summary>
    ''' 空闲的内存块
    ''' </summary>
    Private m_freeIndexPool As Stack(Of Integer)
    ''' <summary>
    ''' 当前的偏移量
    ''' </summary>
    Private m_currentIndex As Integer
    ''' <summary>
    ''' 每一个块的大小
    ''' </summary>
    Private m_ChunkSize As Integer
    Public Property Node As LinkedListNode(Of BufferChunkManage)

    ''' <summary>
    ''' 创建一个内存块
    ''' </summary>
    ''' <param name="chunkCapacity">总的虚拟块数</param>
    ''' <param name="ChunkSize">每一个块的大小</param>
    Public Sub New(ByVal chunkCapacity As Integer, ByVal ChunkSize As Integer)
        m_ChunkCapacity = chunkCapacity
        m_ChunkSize = ChunkSize
        m_currentIndex = 0
        m_freeIndexPool = New Stack(Of Integer)()
        m_numBytes = m_ChunkCapacity * m_ChunkSize

        m_buffer = New Byte(m_numBytes - 1) {}
    End Sub


    Public Function GetBuffer(ByRef buf As BufferChunk) As Boolean
        If m_freeIndexPool.Count > 0 Then
            buf = New BufferChunk(Me, m_buffer, m_freeIndexPool.Pop(), m_ChunkSize)

        Else
            If (m_numBytes - m_ChunkSize) < m_currentIndex Then
                Return False
            End If
            buf = New BufferChunk(Me, m_buffer, m_currentIndex, m_ChunkSize)
            m_currentIndex += m_ChunkSize
        End If

        Return True
    End Function

    Public Sub FreeBuffer(ByRef buf As BufferChunk)
        If (Object.ReferenceEquals(buf.Manage, Me)) Then
            m_freeIndexPool.Push(buf.Offset)
            buf.Clear()
        End If

    End Sub
End Class
